﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace HelperCommon.Authorizations.IssJWT
{
    public class JwtHelper
    {
        public static string IssueJwt(string id, string Name)
        {
            string iss = "发行人";
            string aud = "受众人";
            string secret = "12345678912345671234567891234567";

            //载荷
            var claims = new List<Claim>()
            {
                 //jwtID唯一
                 new Claim(JwtRegisteredClaimNames.Jti,id),
                 //发行人可以理解为网站属于发行人
                 new Claim(JwtRegisteredClaimNames.Iss,iss),
                 //受众可以理解为哪些人可以使用
                 new Claim(JwtRegisteredClaimNames.Aud,aud),
                 //主体可以理解为对令牌的说明
                 new Claim(JwtRegisteredClaimNames.Sub,"主体"),
                 //发行时间即为令牌生成的时间
                 new Claim (JwtRegisteredClaimNames.Iat,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                 //在此时间之前不可用
                 new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                 //令牌过期时间
                 new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(60)).ToUnixTimeSeconds()}"),
                 new Claim(ClaimTypes.Name,Name)
            };

            //使用密钥生成签名凭证
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //序列化jwt
            var jwt = new JwtSecurityTokenHandler().WriteToken(
                new JwtSecurityToken(
                issuer: iss,
                claims: claims,
                signingCredentials: creds));
            return jwt;
        }
    }
}